#include "imagecycler.h"
#include <QDebug>
#include <QVBoxLayout>


ImageCycler::ImageCycler(QWidget *parent) 
    : QWidget(parent),
    cycleTimer(new QTimer(this))
{
    // 初始化图片显示标签
        imageLabel = new QLabel(this);
        imageLabel->setAlignment(Qt::AlignCenter);// 图片居中显示
        imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
//        imageLabel->setMinimumSize(450,190);  // 设置最小大小
//        imageLabel->setMaximumSize(450,190);
        imageLabel->setScaledContents(true);
        
        // 初始化定时器
        cycleTimer = new QTimer(this);
        connect(cycleTimer, &QTimer::timeout, this, &ImageCycler::onTimerTimeout);
        
        // 使用布局管理器，让 imageLabel 自动填充父控件
            QVBoxLayout *layout = new QVBoxLayout(this);
            layout->setContentsMargins(0, 0, 0, 0);
            layout->addWidget(imageLabel);
}


void ImageCycler::setImagePaths(const QVector<QString> &paths)
{
    imagePaths = paths;
    currentIndex = 0;
    if (!imagePaths.isEmpty()) {
        showCurrentImage();
    }
}

void ImageCycler::addImagePath(const QString &path)
{
    imagePaths.append(path);
    if (imagePaths.size() == 1) {
        showCurrentImage();
    }
}

void ImageCycler::setInterval(int msec)
{
    interval = msec;
    if (cycleTimer->isActive()) {
        cycleTimer->start(interval);
    }
}

void ImageCycler::startCycle()
{
    if (!imagePaths.isEmpty() && !cycleTimer->isActive()) {
        cycleTimer->start(interval);
        emit cycleStarted();
    }
}

void ImageCycler::stopCycle()
{
    if (cycleTimer->isActive()) {
        cycleTimer->stop();
        emit cycleStopped();
    }
}

bool ImageCycler::isCycling() const
{
    return cycleTimer->isActive();
}

void ImageCycler::onTimerTimeout()
{
    if (imagePaths.isEmpty()) return;
    
    currentIndex = (currentIndex + 1) % imagePaths.size();
    showCurrentImage();
    emit imageChanged(currentIndex);
}

void ImageCycler::showCurrentImage()
{
    if (imagePaths.isEmpty()) return;
    QPixmap pixmap(imagePaths.at(currentIndex));
    if (!pixmap.isNull()) {
        imageLabel->setPixmap(pixmap.scaled(imageLabel->size(), 
                                          Qt::KeepAspectRatio, 
                                          Qt::SmoothTransformation));
    }
}

void ImageCycler::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
//    // 调整标签大小为当前widget大小
//    imageLabel->setFixedSize(this->size());
//    if (!imagePaths.isEmpty()) {
//        showCurrentImage();     // 重新缩放当前图片
//    }
    
        showCurrentImage(); // 窗口大小变化时重新缩放图片
}
